<template>
  <div class="map">
    <map id="map" :longitude="longitude" :latitude="latitude" :markers="covers" :polyline="planList"
      :include-points="bounds" @markertap="handleMarker"></map>
    <div v-if="showMarker" class="bottom">
      <wd-button size="small" class="text-12px" @click="openMap">
        导航
      </wd-button>
    </div>
  </div>

</template>

<script setup lang="ts">

onShareAppMessage(() => ({
  title: '地图路径规划',
  path: '/pagesA/map/index'
}));

const showMarker = ref(false)
// 初始坐标设为起点位置
const longitude = ref(120.083021)
const latitude = ref(30.322324)
const bounds = ref([]) // 存储地图边界
const covers = [
  {
    id: 1,
    latitude: 30.322324,
    longitude: 120.083021,
    width: 40,
    height: 40,
    callout: { content: '起点', display: 'ALWAYS' },
    iconPath: '../../static/images/icons/20x20.png'
  },
  {
    id: 2,
    latitude: 30.234905,
    longitude: 120.436328,
    width: 40,
    height: 40,
    callout: { content: '终点', display: 'ALWAYS' },
    iconPath: '../../static/images/icons/20x20.png'
  },
];

// 清洗路线数据
const planList = ref([])
const washData = (steps) => {
  let points = []
  let minLat = Infinity, maxLat = -Infinity
  let minLng = Infinity, maxLng = -Infinity

  steps.forEach(item => {
    const polen = item.polyline.split(';')

    polen.forEach(vv => {
      const [lngStr, latStr] = vv.split(',')
      const lng = parseFloat(lngStr)
      const lat = parseFloat(latStr)

      points.push({ longitude: lng, latitude: lat })

      // 更新边界范围
      minLat = Math.min(minLat, lat)
      maxLat = Math.max(maxLat, lat)
      minLng = Math.min(minLng, lng)
      maxLng = Math.max(maxLng, lng)
    })
  })

  // 设置地图中心点为路线中心（但不添加标记）
  longitude.value = (minLng + maxLng) / 2
  latitude.value = (minLat + maxLat) / 2

  // 添加边界缓冲
  const latBuffer = (maxLat - minLat) * 0.05
  const lngBuffer = (maxLng - minLng) * 0.05

  bounds.value = [
    { latitude: minLat - latBuffer, longitude: minLng - lngBuffer },
    { latitude: maxLat + latBuffer, longitude: maxLng + lngBuffer }
  ]

  planList.value = [{
    points,
    width: 4,
    arrowLine: true,
    color: '#204CF1',
  }]
}
const key = 'b973e829645e9f85e22ec0f669d5047b'

// 获取地理位置（保持原样）
const getLocation = (address: string): Promise<string> => {
  return new Promise((resolve) => {
    uni.request({
      url: `https://restapi.amap.com/v3/geocode/geo?address=${address}&key=${key}`,
      success: (res) => {
        if (res.data.geocodes.length) {
          resolve(res.data.geocodes[0].location)
        }
      }
    });
  })
}

// 路径规划（保持原样）
const getDriving = async () => {
  const origin = await getLocation('杭州三墩')
  const destination = await getLocation('萧山机场')
  uni.request({
    url: `https://restapi.amap.com/v3/direction/driving?origin=${origin}&destination=${destination}&key=${key}`,
    success: (res) => {
      const data = res.data.route
      if (data.paths?.[0]?.steps) {
        washData(data.paths[0].steps)
      }
    }
  });
}

const currentLocation = ref({
  latitude: 0,
  longitude: 0,
})
const handleMarker = (e) => {
  console.log('打印***e', e.detail.markerId)
  const id = e.detail.markerId
  const find = covers.find(item => item.id === id)
  currentLocation.value.latitude = find?.latitude
  currentLocation.value.longitude = find?.longitude
  showMarker.value = !showMarker.value
}

const openMap = () => {
  uni.openLocation({
    latitude: currentLocation.value.latitude,
    longitude: currentLocation.value.longitude,
    // scale: 28
  });
}

// 初始化加载
getDriving()
</script>

<style lang="scss" scoped>
.map {
  position: relative;

  #map {
    width: 100vw;
    height: 100vh;
  }

  .bottom {
    height: 50px;
    position: absolute;
    bottom: 10px;
    left: 10px;
    right: 10px;
    background: #ccc;
  }

}
</style>
